<?php
Yii::import('application.components.facebook.Facebook');

class SiteController extends Controller
{
	public $layout='//layouts/home';

	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
				// captcha action renders the CAPTCHA image displayed on the contact page
				'captcha'=>array(
						'class'=>'CCaptchaAction',
						'backColor'=>0xFFFFFF,
				),
				// page action renders "static" pages stored under 'protected/views/site/pages'
				// They can be accessed via: index.php?r=site/page&view=FileName
				'page'=>array(
						'class'=>'CViewAction',
				),
		);
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex($category_id = null)
	{
		// renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
		$this->pageTitle = Yii::app()->name;
		$criteria=new CDbCriteria;
		$criteria->condition='t.status>='.Event::STATUS_ACTIVE;
		$criteria->order= "start desc";
		if(!empty($category_id)){
			$criteria->condition .= " and t.category_id = $category_id";
		}
		
		$pages = new CPagination(Event::model() -> count($criteria));
		$pages -> pageSize =15;
		$pages -> applyLimit($criteria);
		
		$events = Event::model()->with('category')->with('member')->findAll($criteria);
		
		$this->render('index',
				array("events"=>$events,'pages'=>$pages)
		);
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
		if($error=Yii::app()->errorHandler->error)
		{
			if(Yii::app()->request->isAjaxRequest)
				echo $error['message'];
			else
				$this->render('error', $error);
		}
	}

	/**
	 * Displays the contact page
	 */
	public function actionContact()
	{
		$this->pageTitle = "联系我们 - ".Yii::app()->name;
		$model=new ContactForm;
		if(isset($_POST['ContactForm']))
		{
			$model->attributes=$_POST['ContactForm'];
			if($model->validate())
			{
				$headers="From: {$model->email}\r\nReply-To: {$model->email}";
				mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers);
				Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
				$this->refresh();
			}
		}
		$this->render('contact',array('model'=>$model));
	}

	public function facebookLogin(){
		//facebook login
		$facebook = new Facebook(Constants::$facebook_config);
		$user = $facebook->getUser();
		if($user){
			$user_profile = $facebook->api('/me');
			//print_r($user_profile);exit;
			//example: Array ( [id] => 753482649 [name] => Evan Lee [first_name] => Evan [last_name] => Lee [link] => http://www.facebook.com/evan.lee.lee [username] => evan.lee.lee [timezone] => 8 [locale] => en_US [verified] => 1 [updated_time] => 2012-01-30T15:27:49+0000 )
			$username = 'FB'.$user_profile['id'];
			$member = Member::model()->find("username = '$username'");
			if(empty($member)){
				$member = new Member();
				$member->username = $username;
				$member->login_from = Member::LOGIN_FROM_FACEBOOK;
				$member->name = $user_profile['name'];
				$member->password=hash("md5","");
				$member->status = Member::STATUS_FEATURED;
				$member->type = Member::TYPE_USER;
				$member->save(false);
			}
			$identity=new UserIdentity($username, "");
			if($identity->authenticate()){
				Yii::app()->user->login($identity);
			}
			if (strpos(Yii::app()->user->returnUrl,"login") === false){
				$this->redirect(Yii::app()->user->returnUrl);
			}else{
				$this->redirect(Yii::app()->homeUrl);
			}
		}
	}
	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
		$this->facebookLogin();

		$model=new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login())
				$this->redirect(Yii::app()->user->returnUrl);
		}
		// display the login form
		$this->render('login',array('model'=>$model));
	}

	public function actionRegister(){
		$this->pageTitle="用户注册 - ".Yii::app()->name;
		$member = new Member();
		$member->type="user";
		if(isset($_POST['Member'])){
			$member->attributes = $_POST['Member'];
			$member->status=Member::STATUS_ACTIVE;
			$member->type = Member::TYPE_GROUP;
			$member->avatar = $_POST['Member']['avatar'];
			$member->avatar=CUploadedFile::getInstance($member,'avatar');
			if($member->validate()){
				$password = $member->password;
				$member->password =hash('md5',$_POST['Member']['password']);
				if($member->save()){
					//upload avatar
					if(!empty($member->avatar)){  //upload event front cover image
						$filepath = Utils::getImagePathById("avatar", "", $member->id);
						$filepath_thumbnail = Utils::getImagePathById("avatar", "thumbnail", $member->id);
						$member->avatar->saveAs($filepath);
						$image = new Image();
						ImageUtils::resize($filepath,$filepath,150,150,true);
						ImageUtils::resize($filepath,$filepath_thumbnail,50,50,true);
					}

					//Login
					$model=new LoginForm;
					$model->username = $member->username;
					$model->password = $password;
					$model->login();
					$this->redirect(array("site/index"));
					CApplication::end();
				}
			}else{
				$this->render('register',array('member'=>$member));
				return;
			}
		}

		//	$user->password=null;
		$this->render('register',array('member'=>$member));
	}
	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}
}
